<template>
  <!-- 通讯录列表 -->
  <ul v-if="!contactSearchingStatus" class="tui-contact-list-h5" >
    <li
      v-for="(contactListObj, key) in contactListMap"
      :key="key" class="tui-contact-list-item" style="border-bottom: 1px solid #eee;"
    >
	  <!-- 顶部开始 -->
      <header class="tui-contact-list-item-header" @click="toggleCurrentContactList(key)" >
		<!-- 头像与列表 -->
        <div class="tui-contact-list-item-header-left" style="display: flexbox;">
		  <image :src="contactListObj.imgUrl" style="height: 42px; width: 42px; margin-right: 8px;" mode=""></image>
          <div>{{ TUITranslateService.t(`TUIContact.${contactListObj.title}`) }}</div>
        </div>
		<!-- 右侧是否展开 还是 封闭 是否有未读消息 -->
        <div class="tui-contact-list-item-header-right">
		  <Icon :file="currentContactListKey === key ? downSVG : rightSVG" width="16px" height="16px" />
          <span v-if="contactListObj.unreadCount" class="tui-contact-list-item-header-right-unread" >
            {{ contactListObj.unreadCount }}
          </span>
        </div>
      </header>
	  <!-- 顶部 结束 -->
	  
	  <!-- 好友列表 -->
      <ul :class="['tui-contact-list-item-main', currentContactListKey === key ? '' : 'hidden']">
        <li
          v-for="contactListItem in contactListObj.list.filter(i => i)"
          :key="contactListItem.renderKey"
          class="tui-contact-list-item-main-item"
          :class="['selected']"
          @click="selectItem(contactListItem)"
		  style="border-bottom: 1px solid #eee;"
        >	  
		  <ContactListItem
		    v-if="isValidContactItem(contactListItem)"
		    :key="contactListItem.renderKey"
		    :item="deepCopy(contactListItem)"
		    :displayOnlineStatus="displayOnlineStatus && key === 'friendList'"
		  />
		  <div v-else class="contact-letter-item">
		    {{ contactListItem.letter }}
		  </div>

        </li>
      </ul>
    </li>
  </ul>
  
  <!-- 通讯录 搜索 结果展示-->
  <ul v-else class="tui-contact-list" >
    <li v-for="(item, key) in contactSearchResult" :key="key" class="tui-contact-list-item" >
      <div v-if="item.list[0]" class="tui-contact-search-list" >
        <div class="tui-contact-search-list-title">
          {{ TUITranslateService.t(`TUIContact.${item.label}`) }}
        </div>
        <div
          v-for="(listItem, index) in item.list"
          :key="index"
          class="tui-contact-search-list-item"
          :class="['selected']"
          @click="selectItem(listItem)"
        >
          <ContactListItem
            :item="listItem"
            :displayOnlineStatus="false"
          />
        </div>
      </div>
    </li>
	<!-- 如果没有搜索到 -->
    <div
      v-if="isContactSearchNoResult"
      class="tui-contact-search-list-default"
    >
      {{ TUITranslateService.t("TUIContact.无搜索结果") }}
    </div>
  </ul>
</template>
<script setup lang="ts">
import {
  TUITranslateService,
  TUIStore,
  StoreName,
  IGroupModel,
  TUIFriendService,
  Friend,
  FriendApplication,
  TUIUserService,
} from '@tencentcloud/chat-uikit-engine';
import TUICore, { TUIConstants } from '@tencentcloud/tui-core';
import { ref, computed, onMounted, onUnmounted, provide } from '/TUIKit/adapter-vue';
import Icon from '/pages/common/Icon.vue';
import downSVG from '/TUIKit/assets/icon/down-icon.svg';
import rightSVG from '/TUIKit/assets/icon/right-icon.svg';
import {
  IContactList,
  IContactSearchResult,
  IBlackListUserItem,
  IUserStatus,
  IUserStatusMap,
  IContactInfoType,
} from '/TUIKit/interface';
import ContactListItem from './contact-list-item/index.vue';
import { deepCopy } from '/pages/chat/utils/utils';
import { isPC } from '/TUIKit/utils/env';
// 引入拼音扩展组件
import { getInitials } from '/utils/pinyinHelper'

const currentContactListKey = ref<keyof IContactList>('');
const currentContactInfo = ref<IContactInfoType>({} as IContactInfoType);
const contactListMap = ref<IContactList>({
  friendApplicationList: {
    key: 'friendApplicationList',
	imgUrl:'/static/contact/lianxiren.png',
    title: '新的朋友',
    list: [] as FriendApplication[],
    unreadCount: 0,
  },
  blackList: {
    key: 'blackList',
	imgUrl:'/static/contact/heimingdan.png',
    title: '黑名单',
    list: [] as IBlackListUserItem[],
  },
  groupList: {
    key: 'groupList',
	imgUrl:'/static/contact/qunliao.png',
    title: '群聊',
    list: [] as IGroupModel[],
  },
  friendList: {
    key: 'friendList',
	imgUrl:'/static/contact/pengyou.png',
    title: '我的好友',
    list: [] as Friend[],
  },
});
const contactSearchingStatus = ref<boolean>(false);
const contactSearchResult = ref<IContactSearchResult>();
const displayOnlineStatus = ref<boolean>(false);
const userOnlineStatusMap = ref<IUserStatusMap>();

// 判断是否 搜索到了 用户 或者群组 
const isContactSearchNoResult = computed((): boolean => {
  return (
    !contactSearchResult?.value?.user?.list[0]
    && !contactSearchResult?.value?.group?.list[0]
  );
});


// 挂载自动执行 
onMounted(() => {
  TUIStore.watch(StoreName.APP, {
    enabledCustomerServicePlugin: onCustomerServiceCommercialPluginUpdated,
  });

  TUIStore.watch(StoreName.GRP, {
    groupList: onGroupListUpdated,
  });

  TUIStore.watch(StoreName.USER, {
    userBlacklist: onUserBlacklistUpdated,
    displayOnlineStatus: onDisplayOnlineStatusUpdated,
    userStatusList: onUserStatusListUpdated,
  });

  TUIStore.watch(StoreName.FRIEND, {
    friendList: onFriendListUpdated,
    friendApplicationList: onFriendApplicationListUpdated,
    friendApplicationUnreadCount: onFriendApplicationUnreadCountUpdated,
  });

  TUIStore.watch(StoreName.CUSTOM, {
    currentContactSearchingStatus: onCurrentContactSearchingStatusUpdated,
    currentContactSearchResult: onCurrentContactSearchResultUpdated,
    currentContactListKey: onCurrentContactListKeyUpdated,
    currentContactInfo: onCurrentContactInfoUpdated,
  });
});

// 卸载 自动去监听 
onUnmounted(() => {
  TUIStore.unwatch(StoreName.APP, {
    enabledCustomerServicePlugin: onCustomerServiceCommercialPluginUpdated,
  });

  TUIStore.unwatch(StoreName.GRP, {
    groupList: onGroupListUpdated,
  });

  TUIStore.unwatch(StoreName.USER, {
    userBlacklist: onUserBlacklistUpdated,
    displayOnlineStatus: onDisplayOnlineStatusUpdated,
    userStatusList: onUserStatusListUpdated,
  });

  TUIStore.unwatch(StoreName.FRIEND, {
    friendList: onFriendListUpdated,
    friendApplicationList: onFriendApplicationListUpdated,
    friendApplicationUnreadCount: onFriendApplicationUnreadCountUpdated,
  });

  TUIStore.unwatch(StoreName.CUSTOM, {
    currentContactSearchingStatus: onCurrentContactSearchingStatusUpdated,
    currentContactSearchResult: onCurrentContactSearchResultUpdated,
    currentContactListKey: onCurrentContactListKeyUpdated,
    currentContactInfo: onCurrentContactInfoUpdated,
  });
});

function isValidContactItem(item: any) {
  return item?.userID || item?.groupID || item?.customID;
}

// 列表折叠 开启
function toggleCurrentContactList(key: keyof IContactList) {
  if (currentContactListKey.value === key) {
    currentContactListKey.value = '';
    currentContactInfo.value = {} as IContactInfoType;
    TUIStore.update(StoreName.CUSTOM, 'currentContactListKey', '');
    TUIStore.update(StoreName.CUSTOM, 'currentContactInfo', {} as IContactInfoType);
  } else {
    currentContactListKey.value = key;
    TUIStore.update(StoreName.CUSTOM, 'currentContactListKey', key);
    if (key === 'friendApplicationList') {
      TUIFriendService.setFriendApplicationRead();
    }
  }
}

// 点击选择 这个条目
function selectItem(item: any) {
	// 如果是 排序字母 不做任何处理
	if(item?.letter){
		return true;
	}
  // 当前选中通讯录用户信息 
  currentContactInfo.value = item;
  // For a result in the search list, before viewing the contactInfo details,
  // it is necessary to update the data for the "already in the group list/already in the friend list" situation to obtain more detailed information
  // 如果是 搜索状态下 获取到的 通讯录数据
  if (contactSearchingStatus.value) {
	// 临时存有的值
    let targetListItem;
    if ((currentContactInfo.value as Friend)?.userID) {
	// 如果是好友
      targetListItem = contactListMap.value?.friendList?.list?.find(
        (item: IContactInfoType) => (item as Friend)?.userID === (currentContactInfo.value as Friend)?.userID,
      );
    } else if ((currentContactInfo.value as IGroupModel)?.groupID) {
	// 如果是群组
      targetListItem = contactListMap.value?.groupList?.list?.find(
        (item: IContactInfoType) => (item as IGroupModel)?.groupID === (currentContactInfo.value as IGroupModel)?.groupID,
      );
    }
	// 如果查找到里面有这个数据
    if (targetListItem) {
      currentContactInfo.value = targetListItem;
    }
  }
  // 非搜索状态 以及 搜索状态 都更新 当前 状态到 用户的值
  TUIStore.update(StoreName.CUSTOM, 'currentContactInfo', currentContactInfo.value);
}

// 更新用户在线状态显示
function onDisplayOnlineStatusUpdated(status: boolean) {
  displayOnlineStatus.value = status;
}

/*
这段代码定义了一个处理用户在线状态更新的函数。它将一个 Map<string, IUserStatus> 
类型的列表转换为普通对象，然后赋值给响应式变量 userOnlineStatusMap.value。

这个函数的功能就是转化一下格式
*/
function onUserStatusListUpdated(list: Map<string, IUserStatus>) {
  if (list?.size > 0) {
	/*
	核心逻辑：将 Map 转换为普通对象。
	Map.entries() 会返回一个 iterator，形如：[['user1', status1], ['user2', status2], ...]
	Object.fromEntries() 把这个 iterator 转换成对象：
	{
	  user1: status1,
	  user2: status2
	}
	*/
    userOnlineStatusMap.value = Object.fromEntries(list?.entries());
  }
}

function onCustomerServiceCommercialPluginUpdated(isEnabled: boolean) {
  if (!isEnabled) {
    return;
  }

  // After the customer purchases the customer service plug-in,
  // the engine updates the enabledCustomerServicePlugin to true through the commercial capability bit.
  const contactListExtensionID = TUIConstants.TUIContact.EXTENSION.CONTACT_LIST.EXT_ID;
  const tuiContactExtensionList = TUICore.getExtensionList(contactListExtensionID);

  const customerData = tuiContactExtensionList.find((extension: any) => {
    const { name, accountList = [] } = extension.data || {};
    return name === 'customer' && accountList.length > 0;
  });

  if (customerData) {
    const { data, text } = customerData;
    const { accountList } = (data || {}) as { accountList: string[] };

    TUIUserService.getUserProfile({ userIDList: accountList })
      .then((res) => {
        if (res.data.length > 0) {
          const customerList = {
            title: text,
            list: res.data.map((item: any, index: number) => {
              return {
                ...item,
                renderKey: generateRenderKey('customerList', item, index),
                infoKeyList: [],
                btnKeyList: ['enterC2CConversation'],
              };
            }),
            key: 'customerList',
          };
          contactListMap.value = { ...contactListMap.value, customerList };
        }
      })
      .catch(() => { });
  }
}

function onGroupListUpdated(groupList: IGroupModel[]) {
  updateContactListMap('groupList', groupList);
}

function onUserBlacklistUpdated(userBlacklist: IBlackListUserItem[]) {
  updateContactListMap('blackList', userBlacklist);
}

function onFriendApplicationUnreadCountUpdated(friendApplicationUnreadCount: number) {
  contactListMap.value.friendApplicationList.unreadCount = friendApplicationUnreadCount;
}

function onFriendListUpdated(friendList: Friend[]) {
  // 增加字母 排序能力  
  let newFriendList = getInitials(friendList);
  // console.log("======================friendList================================")
  // console.log(friendList)
  // console.log(newFriendList)
  updateContactListMap('friendList', newFriendList);
}

function onFriendApplicationListUpdated(friendApplicationList: FriendApplication[]) {
  updateContactListMap('friendApplicationList', friendApplicationList);
}

function updateContactListMap(key: keyof IContactList, list: IContactInfoType[]) {
  contactListMap.value[key].list = list;
  contactListMap.value[key].list.map((item: IContactInfoType, index: number) => item.renderKey = generateRenderKey(key, item, index));
  updateCurrentContactInfoFromList(contactListMap.value[key].list, key);
}

function updateCurrentContactInfoFromList(list: IContactInfoType[], type: keyof IContactList) {
  if (
    !(currentContactInfo.value as Friend)?.userID
    && !(currentContactInfo.value as IGroupModel)?.groupID
  ) {
    return;
  }
  if (type === currentContactListKey.value || contactSearchingStatus.value) {
    currentContactInfo.value = list?.find(
      (item: any) =>
        (item?.groupID && item?.groupID === (currentContactInfo.value as IGroupModel)?.groupID) || (item?.userID && item?.userID === (currentContactInfo.value as Friend)?.userID),
    ) || {} as IContactInfoType;
    TUIStore.update(StoreName.CUSTOM, 'currentContactInfo', currentContactInfo.value);
  }
}

function generateRenderKey(contactListMapKey: keyof IContactList, contactInfo: IContactInfoType, index: number) {
  return `${contactListMapKey}-${(contactInfo as Friend).userID || (contactInfo as IGroupModel).groupID || ('index' + index)}`;
}

function onCurrentContactSearchResultUpdated(searchResult: IContactSearchResult) {
  contactSearchResult.value = searchResult;
}

function onCurrentContactSearchingStatusUpdated(searchingStatus: boolean) {
  contactSearchingStatus.value = searchingStatus;
  TUIStore.update(StoreName.CUSTOM, 'currentContactInfo', {} as IContactInfoType);
  TUIStore.update(StoreName.CUSTOM, 'currentContactListKey', '');
}

function onCurrentContactInfoUpdated(contactInfo: IContactInfoType) {
  currentContactInfo.value = contactInfo;
}

function onCurrentContactListKeyUpdated(contactListKey: string) {
  currentContactListKey.value = contactListKey;
}

provide('userOnlineStatusMap', userOnlineStatusMap);
</script>

<style lang="scss" scoped src="./style/index.scss"></style>
<style>
	.contact-letter-item {
	  height: 40px;  /* 调整高度 */
	  background-color: #f5f5f5;  /* 更加柔和的背景色 */
	  display: flex;  /* 使用 Flexbox 来居中内容 */
	  align-items: center;  /* 垂直居中 */
	  justify-content: left;  /* 水平居中 */
	  font-size: 18px;  /* 调整字母大小 */
	  font-weight: bold;  /* 使字母加粗，提升可读性 */
	  color: #333;  /* 字母颜色，适中 */
	  border-radius: 6px;  /* 圆角效果 */
	  margin-bottom: 5px;  /* 增加底部间距，避免和下一个元素太紧凑 */
	  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);  /* 轻微的阴影效果，增加立体感 */
	  text-transform: uppercase;  /* 字母大写，增强视觉冲击 */
	}

</style>
